﻿namespace Nello
{
    using System;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;

    public class DESUtil
    {
        public const string KEY = "h /o@~@m";

        public static string Decrypt(string origin)
        {
            return Decrypt(origin, "h /o@~@m");
        }

        public static string Decrypt(string origin, string key)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = new byte[origin.Length / 2];
                for (int x = 0; x < (origin.Length / 2); x++)
                {
                    int i = Convert.ToInt32(origin.Substring(x * 2, 2), 0x10);
                    inputByteArray[x] = (byte) i;
                }
                des.Key = Encoding.ASCII.GetBytes(key);
                des.IV = Encoding.ASCII.GetBytes(key);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Encoding.Default.GetString(ms.ToArray());
            }
            catch
            {
                return "";
            }
        }

        public static string Encrypt(string origin)
        {
            return Encrypt(origin, "h /o@~@m");
        }

        public static string Encrypt(string origin, string key)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(origin);
            des.Key = Encoding.ASCII.GetBytes(key);
            des.IV = Encoding.ASCII.GetBytes(key);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();
        }
    }
}

